# forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, TextAreaField, SubmitField, SelectField, FileField
from wtforms.validators import DataRequired, Email, Length, EqualTo, ValidationError
from flask_wtf.file import FileAllowed
from models import User

# 登录表单
class LoginForm(FlaskForm):
    email = StringField('邮箱', validators=[DataRequired(), Email()])
    password = PasswordField('密码', validators=[DataRequired()])
    submit = SubmitField('登录')

# 注册表单
class RegistrationForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(min=2, max=20)])
    email = StringField('邮箱', validators=[DataRequired(), Email()])
    password = PasswordField('密码', validators=[DataRequired(), Length(min=6)])
    confirm_password = PasswordField('确认密码', validators=[
        DataRequired(), 
        EqualTo('password', message='两次输入的密码不一致')
    ])
    submit = SubmitField('注册')
    
    # 自定义验证器 - 检查用户名是否已存在
    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user:
            raise ValidationError('该用户名已被占用，请选择其他用户名')
    
    # 自定义验证器 - 检查邮箱是否已存在
    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user:
            raise ValidationError('该邮箱已被注册，请使用其他邮箱')

# 作品上传表单
class PhotoForm(FlaskForm):
    title = StringField('作品标题', validators=[DataRequired(), Length(max=100)])
    description = TextAreaField('作品描述', validators=[Length(max=500)])
    category = SelectField('作品类别', choices=[
        ('风景', '风景'),
        ('人像', '人像'),
        ('建筑', '建筑'),
        ('动物', '动物'),
        ('其他', '其他')
    ])
    image = FileField('上传图片', validators=[DataRequired(), FileAllowed(['jpg', 'jpeg', 'png', 'gif'], '只支持图片格式')])
    submit = SubmitField('提交作品')

# 用户资料编辑表单
class ProfileForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(min=2, max=20)])
    bio = TextAreaField('个人简介', validators=[Length(max=500)])
    gender = SelectField('性别', choices=[
        ('', '请选择'),
        ('male', '男'),
        ('female', '女'),
        ('other', '其他')
    ])
    avatar = FileField('上传头像', validators=[FileAllowed(['jpg', 'jpeg', 'png'], '只支持图片格式')])
    submit = SubmitField('更新资料')

# 评论表单
class CommentForm(FlaskForm):
    content = TextAreaField('评论', validators=[DataRequired(), Length(max=500)])
    submit = SubmitField('发表评论')

# 搜索表单
class SearchForm(FlaskForm):
    query = StringField('搜索', validators=[DataRequired()])
    submit = SubmitField('搜索')